import pymysql
from pyecharts.charts import Pie
from pyecharts import options as opts

# 数据库连接配置
db = pymysql.connect(
    host="localhost",
    port=3306,
    user="root",
    database="crawlerdemo",
    password="woshiliuhao0",
    charset="utf8"
)

cursor = db.cursor()

sql = "select job_place, min(job_sal) from job group by job_place"

try:
    cursor.execute(sql)
    res = cursor.fetchall()

    # 准备扇形图的数据
    cities = [item[0] for item in res]  # 城市名称
    salaries = [item[1] for item in res]  # 对应的最低薪水

    # 创建扇形图
    pie = Pie()
    pie.add(
        series_name="最低薪水",
        data_pair=list(zip(cities, salaries)),  # 将城市和薪水组合成元组列表
        radius=["30%", "75%"]  # 设置扇形图的内外半径
    )

    # 设置全局配置项
    pie.set_global_opts(
        title_opts=opts.TitleOpts(title="各城市的最低薪水分布"),  # 图表标题
        legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%")  # 图例设置
    )

    # 设置系列配置项
    pie.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))  # 设置数据标签格式

    # 渲染到HTML文件中
    pie.render("barmin.html")
except Exception as e:
    print(e)
    print("查询或图表创建出现问题")
finally:
    # 关闭数据库连接
    cursor.close()
    db.close()